import { login, logout, getUserList } from '@/api/user' // getInfo
import { getToken, setToken, removeToken, removeCurrentRegionid, removeCurrentTitle, removeFirstLogin, removeCurrentLineId, setLogedUser, getLogedUser, removeLogedUser } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { defaultRoles } from '@/api/default-apis'
const state = {
  token: getToken(),
  name: '',
  nickName: '',
  roleRegion: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_NICKNAME: (state, nickName) => {
    state.nickName = nickName
  },
  SET_ROLEREGION: (state, roleRegion) => {
    state.roleRegion = roleRegion
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        defaultRoles().then(res => {
          const roleList = res.roleList
          const currentRole = roleList.filter(item => {
            return item.roleId === response.roleId
          })[0]
          const token = currentRole.roleCode + '-token'
          commit('SET_TOKEN', token)
          setToken(token)
          const resRegion = response.regionId
          const userobj = {
            userName: username,
            nickName: '',
            regionId: resRegion, // response.regionId
            roleId: response.roleId
          }
          console.log('userobj', userobj)
          setLogedUser(userobj)
          commit('SET_ROLEREGION', resRegion) // response.regionId
          commit('SET_NAME', username)
          resolve()
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      let roleList = []
      defaultRoles().then(res => {
        roleList = res.roleList
      }).then(() => {
        getUserList().then(response => {
          const logedUser = JSON.parse(getLogedUser())
          // console.log(logedUser)
          const userList = response.data
          const curUser = userList.filter(item => {
            return item.userName === logedUser.userName
          })[0]
          const role = roleList.filter(item => {
            return item.roleId === curUser.roleId
          })[0]
          const regionArr = logedUser.regionId.split(',')
          const setRole = [role.roleCode]
          regionArr.forEach(region => {
            setRole.push('VisibleRegion-' + region)
          })
          const data = {
            roles: setRole,
            nickName: curUser.nickName
          }
          // roles must be a non-empty array
          if (!data.roles || data.roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }
          // console.log('getInfo,data.roles', data.roles)
          commit('SET_ROLES', data.roles)
          commit('SET_NICKNAME', data.nickName)
          const userobj = {
            userName: curUser.userName,
            nickName: curUser.nickName,
            regionId: curUser.regionId, // curUser.regionId
            roleId: curUser.roleId
          }
          setLogedUser(userobj)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        removeCurrentRegionid()
        removeCurrentTitle()
        removeFirstLogin()
        removeCurrentLineId()
        removeLogedUser()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
